package com.yc.admin.controller.common;

import com.yc.common.constant.Constant;
import com.yc.common.core.domain.AjaxResult;
import com.yc.common.core.domain.model.LoginBody;
import com.yc.framework.security.context.AuthenticationContextHolder;
import com.yc.framework.service.SysLoginService;
import com.yc.system.domain.SysLoginInfo;
import com.yc.system.service.ISysLoginInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


@RestController
@Slf4j
@Api("登录")
public class LoginController {

    @Resource(name = "sysLoginService")
    private SysLoginService sysLoginService;

    /**
     * 用户登录
     * @param loginBody
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public AjaxResult Login(@RequestBody LoginBody loginBody) {

        System.out.println(loginBody);
        AjaxResult ajax = AjaxResult.success();
        String token = null;
        SysLoginInfo loginInfo = null;

        try {
            // 生成令牌
            token = sysLoginService.login(loginBody.getEmail(), loginBody.getPassword(), loginBody.getCaptcha(),
                    loginBody.getUuid());

            // 从上下文中获取当前用户的登录日志
            loginInfo = AuthenticationContextHolder.getInfo();

        } catch (Exception e) {

            log.error("登录失败：{}", e.getMessage());
            return AjaxResult.error("登录失败：" + e.getMessage());

        } finally {
            AuthenticationContextHolder.clearContext();
        }

        ajax.put(Constant.Authentication.TOKEN, token);
        ajax.put("loginInfo", loginInfo);
        return ajax;
    }
}
